import { Command } from "@/hooks/use-commander"

const signs = ['', '}', '"}']
export const extractJsonContent = (text: string, name: string) => {
    let result = ''
    signs.forEach(sign => {
        try {
            const content = JSON.parse(text + sign)
            if (content.hasOwnProperty(name)) {
                result = content[name]
            }
        } catch { }
    })
    return result
}

export const extractJsonCommands = (text: string): Command[] => {
    const result: Command[] = []
    try {
        const info = JSON.parse(text)
        if (info.HasInstructions) {
            (info.Instructions as any[]).forEach(instruction => {
                let tool = (instruction.tool as string).split('.')
                let args = instruction.args ?? {}
                if (tool[tool.length - 1].toLowerCase().indexOf('parallel') != -1) {
                    (args.tool_uses as any[]).forEach(item => {
                        tool = (item.recipient_name as string).split('.')
                        args = item.parameters ?? {}
                        result.push({
                            tool: tool[tool.length - 1],
                            action: args.action ?? tool[tool.length - 1],
                            target: args.target,
                            property: args.property,
                            value: args.value
                        })
                    })
                } else {
                    result.push({
                        tool: tool[tool.length - 1],
                        action: args.action ?? tool[tool.length - 1],
                        target: args.target,
                        property: args.property,
                        value: args.value
                    })
                }
            })
        }
    } catch { }

    return result
}